<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>在线聊天室</title>
    <script src="https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.min.js"></script>
    <style>
        /* 基础样式 */
        body {
            font-family: "Microsoft YaHei", Arial, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 10px;
            box-sizing: border-box;
        }

        /* 登录界面响应式设计 */
        #login-screen {
            max-width: 400px;
            margin: 20px auto;
            padding: 20px;
            text-align: center;
        }

        #login-screen input {
            width: 100%;
            padding: 10px;
            margin-bottom: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            box-sizing: border-box;
        }

        #login-screen button {
            width: 100%;
            padding: 10px;
            background: #1976d2;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        /* 聊天界面容器 */
        .container {
            display: flex;
            gap: 20px;
            height: calc(100vh - 100px); /* 减去标题栏的高度 */
            margin-top: 10px;
        }

        /* 聊天主区域 */
        .chat-container {
            flex: 1;
            min-width: 0; /* 防止flex子项溢出 */
            display: flex;
            flex-direction: column;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            background: #fff;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }

        /* 侧边栏 */
        #sidebar {
            width: 250px;
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        /* 输入区域响应式设计 */
        .input-container {
            display: flex;
            gap: 8px;
            padding: 10px;
            background: #fff;
            border-top: 1px solid #e0e0e0;
            flex-wrap: wrap;
        }

        .input-container input[type="text"] {
            flex: 1;
            min-width: 150px;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }

        .input-container button {
            padding: 8px 12px;
            white-space: nowrap;
        }

        /* 消息气泡响应式设计 */
        .message-bubble {
            max-width: 80%;
            word-break: break-word;
        }

        /* 媒体查询 - 平板设备 */
        @media (max-width: 768px) {
            .container {
                flex-direction: column;
                height: calc(100vh - 20px);
            }

            #sidebar {
                width: 100%;
                flex-direction: row;
                height: 150px;
            }

            .sidebar-section {
                flex: 1;
                min-width: 0;
            }

            .chat-container {
                height: calc(100vh - 170px);
            }
        }

        /* 媒体查询 - 移动设备 */
        @media (max-width: 480px) {
            body {
                padding: 5px;
            }

            .container {
                gap: 10px;
                margin-top: 10px;
            }

            #sidebar {
                flex-direction: column;
                height: auto;
            }

            .sidebar-section {
                height: 120px;
            }

            .chat-container {
                height: calc(100vh - 280px);
            }

            .input-container {
                padding: 5px;
            }

            .input-container button {
                padding: 8px;
            }

            .message-bubble {
                max-width: 90%;
            }

            .emoji-button, .profile-button, .file-button {
                padding: 5px;
            }

            .chat-title {
                padding: 10px;
                font-size: 1.1em;
                margin-bottom: 5px;
            }
        }

        emoji-picker {
            width: 100%;
            height: 300px;
            margin-top: 10px;
        }
        .emoji-button {
            font-size: 1.5em;
            cursor: pointer;
            padding: 5px 10px;
            border: none;
            background: none;
        }
        #emojiPicker {
            position: absolute;
            bottom: 60px;
            left: 0;
            background: white;
            border: 1px solid #ccc;
            border-radius: 5px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
            z-index: 1000;
            display: none;
        }
        
        .container {
            display: flex;
            gap: 20px;
            height: 90vh;
            margin-top: 20px;
        }
        
        .chat-container {
            flex: 1;
            display: flex;
            flex-direction: column;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            background: #fff;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        #messages {
            flex: 1;
            overflow-y: auto;
            padding: 20px;
            background: #f5f5f5;
        }
        
        .message-container {
            width: 100%;
            margin: 8px 0;
        }

        .message {
            display: inline-block;
            max-width: 80%;
            min-width: 50px;
            clear: both;
        }

        .message-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 4px;
            padding: 0 4px;
        }

        .message-header .sender {
            color: #1976d2;
            font-weight: bold;
        }

        .message-header .timestamp {
            color: #888;
            font-size: 0.8em;
        }

        .message-bubble {
            background: #fff;
            padding: 8px 12px;
            border-radius: 12px;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            white-space: pre-wrap;
            word-wrap: break-word;
        }

        .system-message {
            text-align: center;
            color: #666;
            font-style: italic;
            background: #e8f4f8;
            width: 100%;
            display: block;
            padding: 8px;
            border-radius: 8px;
        }

        .private-message .message-bubble {
            background: #e3f2fd;
        }
        
        .input-container {
            display: flex;
            gap: 10px;
            padding: 15px;
            background: #fff;
            border-top: 1px solid #e0e0e0;
        }
        
        .input-container input {
            flex: 1;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        
        .input-container button {
            padding: 10px 20px;
            background: #1976d2;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        
        .sidebar-section {
            background: #fff;
            border-radius: 8px;
            display: flex;
            flex-direction: column;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            height: calc(50% - 7.5px);  /* 减去gap的一半 */
            min-height: 0;  /* 允许内容区域收缩 */
        }
        
        .sidebar-section h3 {
            margin: 0;
            padding: 10px;
            border-bottom: 1px solid #eee;
            font-size: 14px;
            color: #333;
            background: #fff;
            border-radius: 8px 8px 0 0;
            position: sticky;
            top: 0;
            z-index: 1;
            flex-shrink: 0;  /* 防止标题被压缩 */
        }
        
        .sidebar-content {
            padding: 10px;
            overflow-y: auto;
            flex: 1;
            min-height: 0;  /* 允许内容区域收缩 */
        }
        
        .user-list {
            margin-top: 10px;
        }
        
        .user-item {
            padding: 8px 12px;
            margin: 5px 0;
            border-radius: 4px;
            cursor: pointer;
            transition: background 0.2s;
        }
        
        .user-item:hover {
            background: #f5f5f5;
        }
        
        #currentChat {
            margin-top: 15px;
            padding: 10px;
            background: #e3f2fd;
            border-radius: 4px;
        }
        
        .file-input {
            display: none;
        }
        
        .file-button {
            padding: 10px;
            background: #4CAF50;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        
        .file-message {
            background: #e3f2fd;
            padding: 10px;
            margin: 5px 0;
            border-radius: 4px;
        }
        
        .file-message .file-info {
            display: flex;
            align-items: center;
            gap: 10px;
            margin-top: 5px;
        }
        
        .file-message a {
            color: #1976d2;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 5px;
        }
        
        .file-message a:hover {
            text-decoration: underline;
        }

        .message.error-message {
            width: 100%;
            display: block;
        }

        .error-message .message-bubble {
            background: #ffebee;
            color: #d32f2f;
            border: 1px solid #ffcdd2;
        }

        .error-message .message-header .sender {
            color: #d32f2f;
        }

        .message-bubble a {
            text-decoration: none;
            color: #1976d2;
        }

        .message-bubble a:hover {
            text-decoration: underline;
        }

        #userList, #systemMessages {
            height: 100%;
        }

        .system-log {
            padding: 5px;
            margin: 5px 0;
            font-size: 12px;
            border-radius: 4px;
        }

        .system-log.join {
            background: #e8f5e9;
            color: #2e7d32;
        }

        .system-log.leave {
            background: #fafafa;
            color: #757575;
        }

        .system-log.error {
            background: #ffebee;
            color: #c62828;
        }

        .system-log .timestamp {
            font-size: 0.9em;
            color: #666;
            margin-right: 5px;
        }

        .profile-button {
            font-size: 1.5em;
            cursor: pointer;
            padding: 5px 10px;
            border: none;
            background: none;
        }

        .profile-dialog {
            display: none;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.2);
            z-index: 1000;
        }

        .profile-dialog input {
            margin: 10px 0;
            padding: 8px;
            width: 100%;
            border: 1px solid #ddd;
            border-radius: 4px;
        }

        .profile-dialog button {
            margin-top: 10px;
            padding: 8px 16px;
            background: #1976d2;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }

        .message-bubble.sender-message {
            margin-left: auto;
            border-radius: 12px 12px 2px 12px;
        }
        
        .message-bubble.receiver-message {
            margin-right: auto;
            border-radius: 12px 12px 12px 2px;
        }

        /* 在 style 标签中添加标题栏样式 */
        .chat-title {
            background: #1976d2;
            color: white;
            padding: 15px;
            text-align: center;
            border-radius: 8px 8px 0 0;
            font-size: 1.2em;
            font-weight: bold;
            margin-bottom: 10px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        /* 添加头像相关样式 */
        .avatar {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            margin-right: 8px;
            object-fit: cover;
            background-color: #e0e0e0;
        }

        .message-header {
            display: flex;
            align-items: center;
            margin-bottom: 4px;
            padding: 0 4px;
        }

        .message-info {
            flex: 1;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .avatar-upload {
            text-align: center;
            margin-bottom: 15px;
        }

        .avatar-preview {
            width: 100px;
            height: 100px;
            border-radius: 50%;
            margin: 10px auto;
            display: block;
            object-fit: cover;
            background-color: #e0e0e0;
            cursor: pointer;
        }

        .user-item {
            display: flex;
            align-items: center;
            padding: 8px 12px;
            margin: 5px 0;
            border-radius: 4px;
            cursor: pointer;
            transition: background 0.2s;
        }
    </style>
</head>
<body>
    <div id="login-screen">
        <input type="text" id="username" placeholder="输入用户名">
        <button onclick="connect()">进入聊天室</button>
    </div>

    <div id="chat-screen" style="display: none;">
        <div class="chat-title">
            在线聊天室
        </div>
        <div class="container">
            <div class="chat-container">
                <div id="messages"></div>
                <div class="input-container">
                    <button class="emoji-button" onclick="addEmoji()">😊</button>
                    <button class="profile-button" onclick="showProfileDialog()">👤</button>
                    <input type="text" id="messageInput" placeholder="输入消息">
                    <input type="file" id="fileInput" class="file-input">
                    <button class="file-button" onclick="document.getElementById('fileInput').click()">📎</button>
                    <button onclick="sendMessage()">发送</button>
                </div>
            </div>
            <div id="sidebar">
                <div class="sidebar-section">
                    <h3>在线用户</h3>
                    <div class="sidebar-content" id="userList"></div>
                </div>
                <div class="sidebar-section">
                    <h3>系统消息</h3>
                    <div class="sidebar-content" id="systemMessages"></div>
                </div>
            </div>
        </div>
    </div>

    <div id="profileDialog" class="profile-dialog">
        <h3>修改个人信息</h3>
        <div class="avatar-upload">
            <img id="avatarPreview" class="avatar-preview" src=""
                 onclick="document.getElementById('avatarInput').click()">
            <input type="file" id="avatarInput" style="display: none" accept="image/*">
        </div>
        <input type="text" id="newUsername" placeholder="新用户名">
        <button onclick="updateProfile()">保存</button>
        <button onclick="closeProfileDialog()" style="background: #666;">取消</button>
    </div>

    <script>
        let stompClient = null;
        let username = null;
        let selectedUser = null;
        let userColors = new Map();
        let userAvatars = new Map();

        function getColorForUser(username) {
            if (userColors.has(username)) {
                return userColors.get(username);
            }
            
            // 使用用户名生成一个固定的色调
            let hash = 0;
            for (let i = 0; i < username.length; i++) {
                hash = username.charCodeAt(i) + ((hash << 5) - hash);
            }
            
            // 生成柔和的背景色
            const hue = hash % 360;
            const color = `hsl(${hue}, 70%, 95%)`;
            userColors.set(username, color);
            return color;
        }

        function generateUsername() {
            // 先尝试从 localStorage 获取已存在的用户名
            const savedUsername = localStorage.getItem('chatUsername');
            if (savedUsername) {
                return savedUsername;
            }
            // 如果没有保存的用户名，生成新的
            const newUsername = 'User' + Math.floor(Math.random() * 9000000000 + 1000000000);
            localStorage.setItem('chatUsername', newUsername);
            return newUsername;
        }

        function connect() {
            username = document.getElementById('username').value.trim();
            if (!username) {
                username = generateUsername();
            }
            // 保存用户名到 localStorage
            localStorage.setItem('chatUsername', username);

            const socket = new SockJS('/websocket-chat');
            stompClient = Stomp.over(socket);
            stompClient.connect({}, onConnected, onError);
            
            document.getElementById('login-screen').style.display = 'none';
            document.getElementById('chat-screen').style.display = 'block';

            // 添加心跳检测
            startHeartbeat();
        }

        // 添加心跳检测函数
        function startHeartbeat() {
            setInterval(() => {
                if (stompClient && stompClient.connected) {
                    stompClient.send("/app/chat.heartbeat", {}, JSON.stringify({
                        sender: username,
                        type: 'HEARTBEAT'
                    }));
                }
            }, 30000); // 每30秒发送一次心跳
        }

        // 修改断开连接处理
        function onError(error) {
            console.log('连接错误:', error);
            alert('连接失败，正在重新连接...');
            // 尝试重新连接
            setTimeout(connect, 5000);
        }

        // 添加窗口关闭事件处理
        window.addEventListener('beforeunload', function() {
            if (stompClient) {
                stompClient.send("/app/chat.send", {}, JSON.stringify({
                    sender: username,
                    type: 'LEAVE'
                }));
            }
        });

        function onConnected() {
            // 先订阅用户列表主题，确保能及时接收用户列表更新
            stompClient.subscribe('/topic/users', onUserListReceived);
            
            // 订阅公共消息
            stompClient.subscribe('/topic/public', onMessageReceived);
            
            // 订阅私人消息
            stompClient.subscribe(`/user/${username}/queue/private`, onMessageReceived);
            
            // 发送加入消息，服务器会响应最新的用户列表
            stompClient.send("/app/chat.register", {}, JSON.stringify({
                sender: username,
                type: 'JOIN'
            }));

            // 立即请求当前用户列表
            stompClient.send("/app/chat.users", {}, {});
        }

        function sendMessage() {
            const messageContent = document.getElementById('messageInput').value.trim();
            if (messageContent && stompClient) {
                const chatMessage = {
                    sender: username,
                    content: messageContent,
                    type: 'CHAT'
                };
                
                if (selectedUser) {
                    chatMessage.receiver = selectedUser;
                }
                
                stompClient.send("/app/chat.send", {}, JSON.stringify(chatMessage));
                document.getElementById('messageInput').value = '';
            }
        }

        function onMessageReceived(payload) {
            const message = JSON.parse(payload.body);
            
            // 处理系统消息
            if (message.type === 'JOIN' || message.type === 'LEAVE' || message.type === 'ERROR' || message.type === 'USERNAME_CHANGE') {
                const systemMessage = document.createElement('div');
                systemMessage.className = `system-log ${message.type.toLowerCase()}`;
                
                const timestamp = document.createElement('span');
                timestamp.className = 'timestamp';
                timestamp.textContent = new Date().toLocaleTimeString();
                
                const content = document.createElement('span');
                if (message.type === 'JOIN') {
                    content.textContent = `${message.sender} 加入了聊天室`;
                } else if (message.type === 'LEAVE') {
                    content.textContent = `${message.sender} 离开了聊天室`;
                } else if (message.type === 'ERROR') {
                    content.textContent = message.content;
                } else if (message.type === 'USERNAME_CHANGE') {
                    content.textContent = `${message.sender} 修改用户名为 ${message.content}`;
                }
                
                systemMessage.appendChild(timestamp);
                systemMessage.appendChild(content);
                
                const systemMessagesDiv = document.getElementById('systemMessages');
                systemMessagesDiv.appendChild(systemMessage);
                systemMessagesDiv.scrollTop = systemMessagesDiv.scrollHeight;
            }
            
            // 处理聊天消息
            if (message.type === 'CHAT' || message.type === 'FILE') {
                const messageContainer = document.createElement('div');
                messageContainer.className = 'message-container';
                const messageElement = document.createElement('div');
                messageElement.className = 'message';
                
                const messageHeader = document.createElement('div');
                messageHeader.className = 'message-header';
                
                // 添加头像
                const avatar = document.createElement('img');
                avatar.className = 'avatar';
                avatar.src = userAvatars.get(message.sender) || getDefaultAvatar(message.sender);
                messageHeader.appendChild(avatar);

                const messageInfo = document.createElement('div');
                messageInfo.className = 'message-info';
                messageInfo.innerHTML = `
                    <span class="sender">${message.sender}${message.receiver ? ' 对 ' + message.receiver + ' 说' : ''}</span>
                    <span class="timestamp">${new Date().toLocaleTimeString()}</span>
                `;
                
                messageHeader.appendChild(messageInfo);
                messageElement.appendChild(messageHeader);

                if (message.type === 'FILE') {
                    const messageBubble = document.createElement('div');
                    messageBubble.className = 'message-bubble';
                    
                    // 创建文件下载链接
                    const fileLink = document.createElement('a');
                    fileLink.href = `/files/${message.content}`; // 假设文件存储在 /files 目录下
                    fileLink.target = '_blank';
                    fileLink.innerHTML = `📎 ${message.content} <span style="color: #666;">(点击下载)</span>`;
                    
                    messageBubble.appendChild(fileLink);
                } else {
                    if (message.receiver) {
                        messageElement.classList.add('private-message');
                    }
                    
                    const messageBubble = document.createElement('div');
                    messageBubble.className = 'message-bubble';
                    messageBubble.textContent = message.content;
                    
                    messageElement.appendChild(messageBubble);
                }
                
                messageContainer.appendChild(messageElement);
                const messagesDiv = document.getElementById('messages');
                messagesDiv.appendChild(messageContainer);
                messagesDiv.scrollTop = messagesDiv.scrollHeight;
            }
        }

        function onUserListReceived(payload) {
            const users = JSON.parse(payload.body);
            const userListDiv = document.getElementById('userList');
            userListDiv.innerHTML = '';
            
            if (users && users.length > 0) {
                users.forEach(user => {
                    const userElement = document.createElement('div');
                    userElement.className = 'user-item';
                    
                    const avatar = document.createElement('img');
                    avatar.className = 'avatar';
                    avatar.src = userAvatars.get(user) || getDefaultAvatar(user);
                    userElement.appendChild(avatar);
                    
                    const nameSpan = document.createElement('span');
                    if (user === username) {
                        nameSpan.textContent = `${user} (我)`;
                        nameSpan.style.fontWeight = 'bold';
                    } else {
                        nameSpan.textContent = user;
                        userElement.onclick = () => selectUser(user);
                    }
                    userElement.appendChild(nameSpan);
                    
                    userListDiv.appendChild(userElement);
                });
            } else {
                const emptyMessage = document.createElement('div');
                emptyMessage.className = 'user-item';
                emptyMessage.textContent = '暂无其他在线用户';
                emptyMessage.style.color = '#666';
                emptyMessage.style.fontStyle = 'italic';
                userListDiv.appendChild(emptyMessage);
            }
        }

        function selectUser(user) {
            selectedUser = user;
            document.getElementById('currentChat').textContent = 
                `当前聊天: ${user || '群聊'}`;
        }

        const emojis = ['😊', '😂', '😍', '👍', '😭', '🎉'];
        let currentEmojiIndex = 0;

        function addEmoji() {
            const messageInput = document.getElementById('messageInput');
            messageInput.value += emojis[currentEmojiIndex];
            currentEmojiIndex = (currentEmojiIndex + 1) % emojis.length;
        }

        document.querySelector('emoji-picker')?.addEventListener('emoji-click', event => {
            const messageInput = document.getElementById('messageInput');
            messageInput.value += event.detail.unicode;
            document.getElementById('emojiPicker').style.display = 'none';
        });

        document.addEventListener('click', function(event) {
            const picker = document.getElementById('emojiPicker');
            const emojiButton = document.querySelector('.emoji-button');
            if (picker && !picker.contains(event.target) && event.target !== emojiButton) {
                picker.style.display = 'none';
            }
        });

        // 添加回车键发送消息的功能
        document.getElementById('messageInput').addEventListener('keypress', function(event) {
            if (event.key === 'Enter') {
                event.preventDefault();
                sendMessage();
            }
        });

        // 修改文件处理函数
        document.getElementById('fileInput').addEventListener('change', function(e) {
            if (this.files.length > 0) {
                sendFile();
            }
        });

        function formatFileSize(bytes) {
            if (bytes < 1024) return bytes + ' B';
            else if (bytes < 1048576) return (bytes / 1024).toFixed(2) + ' KB';
            else if (bytes < 1073741824) return (bytes / 1048576).toFixed(2) + ' MB';
            else return (bytes / 1073741824).toFixed(2) + ' GB';
        }

        function sendFile() {
            const fileInput = document.getElementById('fileInput');
            const file = fileInput.files[0];
            
            if (!file) {
                alert('请选择文件');
                return;
            }
            
            const formData = new FormData();
            formData.append('file', file);
            
            // 发送文件到服务器
            fetch('/files/upload', {
                method: 'POST',
                body: formData
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('文件上传失败');
                }
                return response.text();
            })
            .then(filename => {
                // 发送WebSocket消息通知其他用户
                const chatMessage = {
                    sender: username,
                    receiver: selectedUser || null,
                    content: filename,
                    type: 'FILE'
                };
                
                stompClient.send("/app/chat.send", {}, JSON.stringify(chatMessage));
                
                // 清空文件输入框
                fileInput.value = '';
            })
            .catch(error => {
                console.error('Error:', error);
                alert('文件上传失败：' + error.message);
            });
        }

        function getDefaultAvatar(username) {
            // 使用用户名生成颜色
            let hash = 0;
            for (let i = 0; i < username.length; i++) {
                hash = username.charCodeAt(i) + ((hash << 5) - hash);
            }
            const hue = hash % 360;
            return `data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32"><rect width="32" height="32" fill="hsl(${hue}, 70%, 80%)"/><text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle" font-family="Arial" font-size="16" fill="hsl(${hue}, 70%, 30%)">${username[0].toUpperCase()}</text></svg>`;
        }

        function showProfileDialog() {
            const dialog = document.getElementById('profileDialog');
            const input = document.getElementById('newUsername');
            const preview = document.getElementById('avatarPreview');
            input.value = username;
            preview.src = userAvatars.get(username) || getDefaultAvatar(username);
            dialog.style.display = 'block';
        }

        function closeProfileDialog() {
            document.getElementById('profileDialog').style.display = 'none';
        }

        function updateProfile() {
            const newUsername = document.getElementById('newUsername').value.trim();
            const avatarInput = document.getElementById('avatarInput');
            const avatarPreview = document.getElementById('avatarPreview');
            
            // 更新头像
            if (avatarPreview.src) {
                userAvatars.set(newUsername, avatarPreview.src);
            }

            // 更新用户名
            if (newUsername && newUsername !== username) {
                stompClient.send("/app/chat.username", {}, JSON.stringify({
                    sender: username,
                    content: newUsername,
                    type: 'USERNAME_CHANGE'
                }));
                username = newUsername;
                localStorage.setItem('chatUsername', newUsername);
            }

            closeProfileDialog();
        }

        document.getElementById('avatarInput').addEventListener('change', function(e) {
            if (this.files && this.files[0]) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    document.getElementById('avatarPreview').src = e.target.result;
                };
                reader.readAsDataURL(this.files[0]);
            }
        });

        window.onload = function() {
            document.getElementById('username').value = generateUsername();
            connect();
        }
    </script>
</body>
</html> 